package cn.lazyturtle.bugpush.service.dingdingcallback.addressbookevents;

import cn.lazyturtle.bugpush.dao.user.UserDao;
import cn.lazyturtle.bugpush.dto.DingDingUserInfoDto;
import cn.lazyturtle.bugpush.jooq.tables.pojos.BUser;
import cn.lazyturtle.bugpush.service.dingdingcallback.DingDingCallBackHandlerFactory;
import cn.lazyturtle.bugpush.utils.DingTalkUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

import static cn.lazyturtle.bugpush.constant.RedisKeyEnum.USER_NAME_MAP_STRING;

/**
 * <p>
 * UserAddOrgHandler : 用户加入组织事件回调
 * </p>
 *
 * @author cwh
 * @since 2021-10-25
 */
@Component
@Slf4j
public class UserAddOrgHandler extends AbstractAddressBookEventsHandler{
    private final RedisTemplate<String,String> redisTemplate;
    private final DingTalkUtils dingTalkUtils;
    private final UserDao userDao;
    @Autowired
    public UserAddOrgHandler(RedisTemplate<String, String> redisTemplate, DingTalkUtils dingTalkUtils, UserDao userDao) {
        this.redisTemplate = redisTemplate;
        this.dingTalkUtils = dingTalkUtils;
        this.userDao = userDao;
    }

    @Override
    public void dealEvent(JSONObject callBackContent) {
        log.info("通讯录用户增加,callBackContent:{},",callBackContent);
        String userIdList = callBackContent.getString("UserId");
        List<String> userIds = JSONObject.parseArray(userIdList,String.class);
        String userId = userIds.get(0);
        // 根据钉钉userid 查询到 name
        String userInfoDto = dingTalkUtils.getUserInfo(dingTalkUtils.getToken(), userId);
        JSONObject jsonObject = JSONObject.parseObject(userInfoDto);
        DingDingUserInfoDto dingDingUserInfoDto = Optional
            .ofNullable(JSONObject.parseObject(jsonObject.get("result").toString(), DingDingUserInfoDto.class))
            .orElse(new DingDingUserInfoDto());
        log.info("dingDingUserInfoDto:{}",dingDingUserInfoDto);
        BUser bUser = userDao.selectUserByDingDingId(userId);

        // 查询是否有该用户
        if (Objects.isNull(bUser)){
            // 抓包获取所有的用户map key 拼音 value name
            String userName = redisTemplate.opsForValue().get(USER_NAME_MAP_STRING);
            Map<?,?> pinyinUserNameMap = JSONObject.parseObject(userName, Map.class);
            Map<String, String> userNameMap = new HashMap<>(8);
            if (!CollectionUtils.isEmpty(pinyinUserNameMap)){
                Set<?> keySet = pinyinUserNameMap.keySet();
                userNameMap = keySet.stream().collect(Collectors.toMap(k-> pinyinUserNameMap.get(k).toString(),
                    Object::toString));
            }
            String name = dingDingUserInfoDto.getName();
            String mobile = dingDingUserInfoDto.getMobile();
            String pinyinName = userNameMap.get(name);
            BUser user = new BUser().setDingId(userId).setPinyinName(pinyinName).setRealName(name).setPhone(mobile);
            log.info("dingId:{},pinyinName:{},realName:{},phone:{},",userId,pinyinName,name,mobile);
            // 存入数据库
            userDao.insert(user);
        }

    }

    @Override
    public void afterPropertiesSet() {
        DingDingCallBackHandlerFactory.register(USER_ADD_ORG, this);
    }
}
